<template>
    <div id="login">
        <van-nav-bar
        title="登录"
        />
            <van-field
                v-model="mobile"
                required
                label="手机号"
                placeholder="请输入手机号"
                :error-message="mobileError"
                @input="verification"
            />
            <van-field
                v-model="code"
                required
                label="验证码"
                placeholder="请输入验证码(246810)"
                :error-message="codeError"
                @input="verification"
            />
        <div class="btn">
            <van-button type="info" @click="subLogin">登 录</van-button>
        </div>
    </div>
</template>

<script>
import { postLogin } from '@/api/user'
import { mapMutations } from 'vuex'
export default {
  name: 'Login',
  data () {
    return {
      mobile: '18212345678',
      code: '246810',
      mobileError: '',
      codeError: ''
    }
  },
  methods: {
    ...mapMutations('user', ['setTokenInfo']),

    verifyM () {
      if (this.mobile.trim() === '') {
        this.mobileError = '请输入手机号'
        return false
      }
      if (!/^1[3-9]\d{9}$/.test(this.mobile)) {
        this.mobileError = '请输入正确格式的11位手机号'
        return false
      }
      this.mobileError = ''
      return true
    },
    verifyC () {
      if (this.code.trim() === '') {
        this.codeError = '请输入验证码'
        return false
      }
      if (!/^\d{6}$/.test(this.code)) {
        this.codeError = '请输入6位验证码'
        return false
      }
      this.codeError = ''
      return true
    },
    verification () {
      this.verifyM()
      this.verifyC()
    },
    async subLogin () {
      if (this.verifyC && this.verifyM) {
        this.$toast.loading({
          message: '登陆中···',
          forbidClick: true,
          overlay: true
        })
        try {
          const res = await postLogin(
            this.mobile,
            this.code
          )
          this.setTokenInfo(res.data.data)
          this.$toast.success('登录成功')
          this.$router.push('/')
        } catch (error) {
          this.$toast.fail('登录失败，请稍后重试')
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
    #login {
        .btn {
            padding: 20px;
            .van-button {
                font-size: 20px;
                width: 100%;
                border-radius: 6px;
            }
        }
    }
</style>
